import os
import subprocess
import sys
from pathlib import Path
import json
from datetime import datetime


def update_version():
    # 获取当前日期信息
    now = datetime.now()
    year = str(now.year)[-2:]  # 年份后两位
    month = str(now.month)  # 月份，不补零

    # 读取package.json
    package_path = Path(__file__).parent / "package.json"
    with open(package_path, 'r', encoding='utf-8') as f:
        package = json.load(f)

    # 解析当前版本号
    current_version = package["version"]
    major, minor, patch = current_version.split('.')

    # 如果年份或月份不同，重置patch号
    if major != year or minor != month:
        patch = '0'
    else:
        patch = str(int(patch) + 1)  # 自增

    # 更新版本号
    new_version = f"{year}.{month}.{patch}"
    package["version"] = new_version

    # 写回文件
    with open(package_path, 'w', encoding='utf-8') as f:
        json.dump(package, f, indent=2)

    print(f"版本号已更新为: {new_version}")
    return new_version


def build_and_publish():
    # 更新版本号
    update_version()

    # 设置工作目录为yklib项目根目录
    project_dir = Path(__file__).parent.parent / "yklib"
    os.chdir(project_dir)

    print("正在构建项目...")
    subprocess.run("pnpm build", shell=True, check=True)

    print("正在发布包...")
    # 强制使用官方 npm 仓库发布，忽略 .npmrc 配置
    try:
        subprocess.run("npm publish --registry=https://registry.npmjs.org", shell=True, check=True)
    except subprocess.CalledProcessError as e:
        # 检查是否是认证错误
        if "ENEEDAUTH" in str(e):
            print("认证失败，请提供 npm 认证信息:")
            print("1. 如果你有 npm token，请运行: npm set //registry.npmjs.org/:_authToken=YOUR_TOKEN")
            print("2. 如果你没有账户，请先运行: npm adduser")
            sys.exit(1)
        else:
            raise e

    print("发布成功!")


if __name__ == "__main__":
    try:
        build_and_publish()
    except subprocess.CalledProcessError as e:
        print(f"执行失败: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"发生错误: {e}")
        sys.exit(1)
